﻿using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using DotNettyExtensions;
using DotNettyExtensions.entity;
using EasyIot.Common;
using System.Net;
using System.Text;

namespace EasyIot.WebApi.Utility
{
    public class ProtocolBase
    {
        public static void SendProtocol(IChannelHandlerContext ctx, EndPoint point, string uid, int cmd, string msg)
        {
            string taskId = CommonUtility.GenerateRandomCode(16);

            string content = ClientProtocol.SPLIT1 + uid + ClientProtocol.SPLIT1 +
                            taskId + ClientProtocol.SPLIT1 +
                            CommonUtility.SetData(cmd, 2) + ClientProtocol.SPLIT1 +
                            msg + ClientProtocol.SPLIT1;
            StringBuilder bag = new StringBuilder();
            bag.Append(ClientProtocol.HEAD);
            bag.Append(CommonUtility.SetData(CommonUtility.GetLength(content), 4));
            bag.Append(content);
            string protocol = bag.ToString();

            byte[] data = Encoding.UTF8.GetBytes(protocol);
            IByteBuffer initialMessage = Unpooled.Buffer();
            initialMessage.WriteBytes(data);

            object obj = null;

            ChannelEntity channel;
            ServerMgr.dicCtx2Info.TryGetValue(ctx, out channel); 

            switch (channel.ProtocolType)
            {
                case System.Net.Sockets.ProtocolType.Tcp:
                    obj = initialMessage;
                    break;
                case System.Net.Sockets.ProtocolType.Udp:
                    obj = new DatagramPacket(initialMessage, point);
                    break; 
            }  

            ctx.WriteAndFlushAsync(obj);
        }
    }
}
